package com.shanxi.cz.module.biz.framework.mqtt.handler;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class MqttConnectionListener implements MqttCallbackExtended {

    private volatile boolean connected = false;

    @PostConstruct
    public void init() {
        log.info("MQTT连接监听器初始化完成");
    }

    @Override
    public void connectionLost(Throwable cause) {
        connected = false;
        log.error("❌ MQTT连接断开: {}", cause.getMessage());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.debug("收到MQTT消息 - Topic: {}, Qos: {}, Message: {}",
                topic, message.getQos(), new String(message.getPayload()));
    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        connected = true;
        log.info("✅ MQTT连接成功 - 重连: {}, Server: {}", reconnect, serverURI);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.debug("消息投递完成");
    }

    public boolean isConnected() {
        return connected;
    }

}
